﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.Entities;
using JKF.Entities.Model;
using JKF.BusinessLayer.BLL;
using System.Data;
namespace JKF.HandlerLayer.Gift
{
    public partial class GiftsHandler:AHttpHandler
    {

        private static bllGIFTS bllGifts = new bllGIFTS();
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }

        /// <summary>
        /// 添加礼品类别
        /// </summary>
        public void InsertGifts()
        {
            try
            {
                var strScr = P("moduleObj");
                var giftsInfo = this.BuildGIFTSinfoByJson(JsonSerializer.Deserialize<GIFTSinfo_JSON>(strScr), false);
                var tid = giftsInfo.GIFT_KEY;
                bllGifts.Add(giftsInfo);
                var pk = giftsInfo.GIFT_KEY;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "添加成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 修改礼品类别名称
        /// </summary>
        public void EditGifts()
        {
            try
            {
                var strScr = P("moduleObj");
                var giftsInfo = this.BuildGIFTSinfoByJson(JsonSerializer.Deserialize<GIFTSinfo_JSON>(strScr), true);
                var tid = giftsInfo.GIFT_KEY;
                bllGifts.Update(giftsInfo);
                var pk = giftsInfo.GIFT_KEY;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "修改成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 删除礼品类别 
        /// </summary>
        public void DeleteGifts()
        {
            try
            {
                var gift_key = P("id");
                //bllGifts.Delete(new Guid(gift_key));
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = bllGifts.TransactionSQLDeleteBLL(new Guid(gift_key)), Data = gift_key })); 
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 获取礼品类别列表数据
        /// </summary>
        public void GetGifts()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
//GIFT_KEY, , , , MEMO, USER_CREATE, DATE_CREATE, DATE_UPDATE, VALIDITY_PERIOD, SHOP_CODE
            if (P("isExport") == "1")
            {//礼品名称	所属类别	所需积分	有效期至 
                DataTable dt = bllGifts.GetGiftsBLL(P("NAME"), P("NEED_POINT_min"), P("NEED_POINT_max"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount);

                IDictionary<string, string> columns = new Dictionary<string, string>();

                columns.Add("NAME", "礼品名称");
                columns.Add("GIFT_TPYE_KEY", "所属类别");
                columns.Add("NEED_POINT", "所需积分");
                columns.Add("VALIDITY_PERIOD", "有效期至");
                //columns.Add("PURCHASE_PRICE", "进货价格");
                //columns.Add("DATE_CREATE", "录入日期");
                //columns.Add("MEMO", "备注");
                Excel.Export("礼品管理", dt, columns, Response, Excel.PageType.handler);
            }
            else
            {
                obj.Entity = from a in bllGifts.GetGiftsBLL(P("NAME"), P("NEED_POINT_min"), P("NEED_POINT_max"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                             select new
                             {
                                 GIFT_KEY = a.Field<Guid>("GIFT_KEY"),
                                 GIFT_TPYE_KEY = a.Field<string>("GIFT_TPYE_KEY"),
                                 NAME = a.Field<string>("NAME"),
                                 NEED_POINT = a.Field<decimal>("NEED_POINT"),
                                 VALIDITY_PERIOD = a.Field<DateTime>("VALIDITY_PERIOD").ToString("yyyy-MM-dd"),
                                 MEMO = a.Field<string>("MEMO")
                             };

                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
        }

        /// <summary>
        /// 从Json对象构建对象
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="isEdit">是否为编辑</param>
        /// <returns></returns>
        public GIFTSinfo BuildGIFTSinfoByJson(GIFTSinfo_JSON giftsInfo, bool isEdit)
        {//SHOP_CODE, SHOP_NAME, LINKMAN, PHONE, AREA_CODE, ADDRESS, POSTAL_CODE, MEMO, SMS_AVAIBLE, SMS_SENDED, SINGNATURE, USER_CREATE, DATE_CREATE, DATE_UPDATE
            var entity = new GIFTSinfo();
            if (!isEdit) // 添加
            {
                entity.GIFT_KEY = new Guid(DB.GetNewGuid(DB.HR)); //Guid.NewGuid();
            }
            else // 修改
            {
                entity.GIFT_KEY = giftsInfo.GIFT_KEY;
            }
            entity.GIFT_TPYE_KEY = giftsInfo.GIFT_TPYE_KEY;
            entity.NAME = giftsInfo.NAME;
            entity.NEED_POINT = Convert.ToDecimal(giftsInfo.NEED_POINT);
            entity.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE; // 哪个店铺的礼品
            entity.VALIDITY_PERIOD =Convert.ToDateTime( giftsInfo.VALIDITY_PERIOD);
            entity.MEMO = giftsInfo.MEMO;
            entity.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY; // 获取当前用户guid
            entity.DATE_CREATE = System.DateTime.Now;
            return entity;
        }

        /// <summary>
        /// 根据模块group_code获得实体模块信息
        /// </summary>
        public void GetGiftsByCode()
        {
            try
            {
                var scid = P("moduleKey"); 
                var model = bllGifts.GetModel(new Guid(scid)); 
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data =model , FormatString= model.VALIDITY_PERIOD.ToString("yyyy-MM-dd")}));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 检查已输入名称是否存在
        /// </summary>
        public void CheckGiftsName()
        {
            try
            {
                var gift_name = P("GIFT_NAME");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllGifts.ExistsGiftsNameBLL(gift_name) }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 用于组装JSON的类
        /// </summary>
        public class GIFTSinfo_JSON
        {
            public Guid GIFT_KEY;
            public Guid GIFT_TPYE_KEY;
            public string NAME;
            public string NEED_POINT;
            public string MEMO;
            public string VALIDITY_PERIOD;
        }
    }
}
